package com.yc.demo.d0316;

import com.google.gson.Gson;
import com.yc.demo.bean.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "UploadImageServlet", value = "/UploadImageServlet")
@MultipartConfig
public class UploadImageServlet extends HttpServlet {

    public static final String IMAGE_PATH = "D:\\study\\d0318\\";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        Result result;

        try {
            Part image = request.getPart("image");
            //提取文件后缀名
            String suffix = image.getSubmittedFileName()
                    .replaceAll(".+(\\.\\w+)","$1");
            //随机生成文件名
            String filename = UUID.randomUUID().toString();
            filename = filename.replaceAll("-", "");
            filename += suffix;
            //保存文件
            image.write(IMAGE_PATH + filename);
            //构建 上传文件 的 web路径
            String webpath = "/Upload/" + filename;

            result = new Result(1, "文件上传成功", webpath);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result(0, "文件上传失败", null);
        }
        final String json = new Gson().toJson(result);
        response.getWriter().append(json);


    }
}
